package pl.szpadel.android.gadu;

import pl.szpadel.android.gadu.packets.ReceivedPacket;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class ContactListActivity extends ListActivity implements IAppComponent {
	
	/** Logging tag*/
	static final private String TAG = "UserList";
	
	// dialogs
	static final private int DIALOG_IMPORT_CONTACTS = 0;
	static final private int DIALOG_DELETE_CONTACT = 1;
	
	/// Data source for contact list
	private ContactListAdapter mListAdapter;
	private Button mStatusButton;
	
	/// uin of contact selected for removal, or 0 if none
	private long mContactToDelete = 0;
		
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        App.createInstance(getApplicationContext()); // this first - to provide other with context
        App.getInstance().setContactListActivity(this);
        App.getInstance().registerAppComponent(this);
        
        mListAdapter = new ContactListAdapter(App.getInstance().getContactInfoManager());
        setListAdapter(mListAdapter);
        AGLog.d(TAG, "activity starting...");
        
        startService(new Intent(this, CommunicationService.class));
        
        // init ui
        setContentView(R.layout.user_list_window);
        
        mStatusButton = (Button)findViewById(R.id.ContactListStatusButton);
        
        registerForContextMenu(getListView());
        
        // launch logon window 
    	if (!App.getInstance().getConfig().getConnected()) {
    		startActivity(new Intent(this, LogonActivity.class));
    	}

        
        AGLog.i(TAG, "activity created");
        
        
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	
    	if (App.getInstance().getConfig().getConnected()) {
    		updateStatus();
        } else {
        	// turn the status button into 'connect' button
        	mStatusButton.setText(R.string.button_connect);
        	mStatusButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            mStatusButton.setOnClickListener(new View.OnClickListener() {
    			@Override
    			public void onClick(View v) {startActivity(new Intent(ContactListActivity.this, LogonActivity.class));}
    		});
        	
        }
    }
    
    @Override
    public void onDestroy() {
    	super.onDestroy();
        AGLog.i(TAG, "activity destroyed");
        App.getInstance().setContactListActivity(null);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.userlist_activity_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        // -- disconnect --
        case R.id.menu_disconnect: {
        	App.getInstance().getCommunicationService().disconnect();
    		startActivity(new Intent(this, LogonActivity.class));
        	return true;
        }
        // -- settings --
        case R.id.menu_config:
        	startActivity(new Intent(this, SettingsActivity.class));
        	return true;
        // -- import list --
        case R.id.menu_import_contactlist:
        	Toast.makeText(this, R.string.toast_loading_contact_list, Toast.LENGTH_LONG).show();
        	App.getInstance().getContactInfoManager().importContactListFromServer();
        	return true;
		case R.id.menu_add_contact: {
	    	startActivity(new Intent(this, ContactInfoActivity.class));
	    	return true; 
		}
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    /// Handles item click
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	AGLog.i(TAG, "item clicked:" + id);
    	
    	Intent intent = new Intent(this, ChatActivity.class);
    	intent.putExtra(ChatActivity.EXTRA_SENDER, id);
    	startActivity(intent);
    }
    
    /// Handles status button click
    private void onStatusClick() {
    	startActivity(new Intent(this, StatusActivity.class));
    }
    
    /// Updates status button displayed state
    private void updateStatus() {
    	Config cfg = App.getInstance().getConfig();
    	mStatusButton.setText(cfg.getStatus().getDescription());
    	mStatusButton.setCompoundDrawablesWithIntrinsicBounds(cfg.getStatus().getIcon(), 0, 0, 0);
        mStatusButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {onStatusClick();}
		});
    }

	@Override
	public void onPacket(ReceivedPacket packet) {
		// nothing
		
	}

	@Override
	public void onConnectionStateChanged(ConnectionState state) {
		// just connected
		if (state.getState() == ConnectionState.CONNECTED) {
			// check if contact list is empty
			if (App.getInstance().getContactInfoManager().getContacts().isEmpty()) {
				showDialog(DIALOG_IMPORT_CONTACTS);
			}
		}
		
	}

	@Override
	public void onStatusChanged(Status status) {
		updateStatus();
	}

	@Override
	public void onConfigChanged() {
		// nothing
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id) {
		case DIALOG_IMPORT_CONTACTS:
			return new AlertDialog.Builder(this)
				.setMessage(R.string.dialog_inmport_contacts)
                .setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	Toast.makeText(ContactListActivity.this, R.string.toast_loading_contact_list, Toast.LENGTH_LONG).show();
                    	App.getInstance().getContactInfoManager().importContactListFromServer();
                    }
                })
                .setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	// do nothing on 'no'
                    }
                })
                .create();
			
		case DIALOG_DELETE_CONTACT:
			return new AlertDialog.Builder(this)
				.setMessage(R.string.dialog_delete_contact)
                .setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                		App.getInstance().getContactInfoManager().deleteContact(mContactToDelete);
                		mContactToDelete = 0;
                    }
                })
                .setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	// do nothing on 'no'
                    }
                })
                .create();
				
		default:
			return null;
		}
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	  super.onCreateContextMenu(menu, v, menuInfo);
	  // get selected contact id
	  AdapterContextMenuInfo adapterMenuInfo = (AdapterContextMenuInfo)menuInfo;
	  ContactInfo info = App.getInstance().getContactInfoManager().getByUin(adapterMenuInfo.id);
	  if (info != null) {
		  // build menu
		  MenuInflater inflater = getMenuInflater();
		  inflater.inflate(R.menu.contact_list_context_menu, menu);
		  
		  menu.setHeaderTitle(info.displayName);
		  
		  // remove invalid items
		  if (info.mobilePhone.length() == 0) {
			  menu.removeItem(R.id.menu_call);
			  menu.removeItem(R.id.menu_send_text);
		  }
		  if (info.email.length() == 0) menu.removeItem(R.id.menu_send_email);
		  if (info.wwwAdrress.length() == 0) menu.removeItem(R.id.menu_visit_webpage);
	  }
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		ContactInfo contactInfo = App.getInstance().getContactInfoManager().getByUin(info.id);
		switch(item.getItemId()) {
		// chat
		case R.id.menu_chat: {
	    	Intent intent = new Intent(this, ChatActivity.class);
	    	intent.putExtra(ChatActivity.EXTRA_SENDER, info.id);
	    	startActivity(intent);
	    	return true;
	    	}
		case R.id.menu_show_contact_info: {
	    	Intent intent = new Intent(this, ContactInfoActivity.class);
	    	intent.putExtra(ContactInfoActivity.EXTRA_UIN, info.id);
	    	startActivity(intent);
	    	return true; 
	    	}
		case R.id.menu_delete_contact: {
			mContactToDelete = info.id;
			showDialog(DIALOG_DELETE_CONTACT);
	    	return true; 
		}
		case R.id.menu_call: {
			if (contactInfo != null) {
				Uri uri = Uri.parse("tel:" + contactInfo.mobilePhone);
				Intent intent = new Intent(Intent.ACTION_DIAL, uri);
				startActivity(intent);
			}
	    	return true; 
		}
		case R.id.menu_send_text: {
			if (contactInfo != null) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setType("vnd.android-dir/mms-sms");
				intent.putExtra("address", contactInfo.mobilePhone);
				startActivity(intent);
			}
			return true;
		}
		case R.id.menu_send_email: {
			Uri uri = Uri.parse("mailto:" + contactInfo.email);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
			return true;
		}
		case R.id.menu_visit_webpage: {
			String addr = contactInfo.wwwAdrress;
			if (!addr.startsWith("http") && !addr.startsWith("HTTP")){
				addr = "http://" + addr;
			}
			Uri uri = Uri.parse(addr);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
	    	return true; 
		}
	    default:
		    return super.onContextItemSelected(item);
		}
	}

} // class



